import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Button, Space, Table, Tag, Progress, List, Avatar, Spin, Alert } from 'antd';
import { 
  FundOutlined, 
  BarChartOutlined, 
  SettingOutlined, 
  ShoppingCartOutlined, 
  UserOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  PlusOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';

const Dashboard = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [segmentation, setSegmentation] = useState('');
  const [segLoading, setSegLoading] = useState(true);
  const [segError, setSegError] = useState(null);
  const [chatInput, setChatInput] = useState('');
  const [chatHistory, setChatHistory] = useState([]); // {role: 'user'|'ai', content: string}
  const [chatLoading, setChatLoading] = useState(false);

  // 模拟数据
  const portfolioStats = {
    totalValue: 1250000,
    dailyReturn: 2.5,
    monthlyReturn: 8.2,
    totalReturn: 15.6,
    riskLevel: 'medium'
  };

  const recentOrders = [
    { id: 1, type: 'buy', fund: '华夏成长混合', amount: 10000, status: 'pending', time: '2024-01-20 09:30' },
    { id: 2, type: 'sell', fund: '易方达消费行业', amount: 5000, status: 'approved', time: '2024-01-20 10:15' },
    { id: 3, type: 'buy', fund: '嘉实增长混合', amount: 15000, status: 'rejected', time: '2024-01-20 11:00' },
  ];

  const topFunds = [
    { code: '000001', name: '华夏成长混合', return: 15.2, risk: 'medium' },
    { code: '000002', name: '易方达消费行业', return: 18.5, risk: 'high' },
    { code: '000003', name: '嘉实增长混合', return: 12.8, risk: 'medium' },
  ];

  const quickActions = [
    { title: '新增基金', icon: <FundOutlined />, path: '/fund-research', color: '#1890ff' },
    { title: '新建因子', icon: <BarChartOutlined />, path: '/factor-management', color: '#52c41a' },
    { title: '创建策略', icon: <SettingOutlined />, path: '/strategy', color: '#faad14' },
    { title: '新建组合', icon: <ShoppingCartOutlined />, path: '/portfolio', color: '#f5222d' },
    { title: '交易订单', icon: <UserOutlined />, path: '/trade', color: '#722ed1' },
  ];

  const orderColumns = [
    {
      title: '交易类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => (
        <Tag color={type === 'buy' ? 'green' : 'red'}>
          {type === 'buy' ? '买入' : '卖出'}
        </Tag>
      ),
    },
    {
      title: '基金',
      dataIndex: 'fund',
      key: 'fund',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount) => `¥${amount.toLocaleString()}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const colors = { pending: 'orange', approved: 'green', rejected: 'red' };
        const texts = { pending: '待审核', approved: '已批准', rejected: '已驳回' };
        return <Tag color={colors[status]}>{texts[status]}</Tag>;
      },
    },
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
    },
  ];

  const fundColumns = [
    {
      title: '基金代码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '基金名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '收益率',
      dataIndex: 'return',
      key: 'return',
      render: (return_) => (
        <span style={{ color: return_ > 0 ? '#52c41a' : '#f5222d' }}>
          {return_ > 0 ? '+' : ''}{return_}%
        </span>
      ),
    },
    {
      title: '风险等级',
      dataIndex: 'risk',
      key: 'risk',
      render: (risk) => {
        const colors = { low: 'green', medium: 'orange', high: 'red' };
        const texts = { low: '低风险', medium: '中风险', high: '高风险' };
        return <Tag color={colors[risk]}>{texts[risk]}</Tag>;
      },
    },
  ];

  const handleQuickAction = (path) => {
    navigate(path);
  };

  // 页面路径与中文名称映射
  const pageNameMap = {
    '/': '首页',
    '/dashboard': '数据看板',
    '/strategy': '策略管理',
    '/portfolio': '投资组合',
    '/fund-research': '基金研究',
    '/factor-management': '因子管理',
    '/trade': '交易管理',
  };

  // mock分群分析内容
  const mockSegmentation = `
  分群1：活跃用户
  - 特征：频繁访问"策略管理"、"投资组合"等页面，关注收益率和回撤，常用预览和编辑功能。
  - 代表用户：张三、李四

  分群2：新手用户
  - 特征：主要浏览"首页"、"数据看板"、"使用说明"，很少进行实际操作，偶尔查看热门基金。
  - 代表用户：王五、赵六

  分群3：潜在客户
  - 特征：多次访问"投资组合"、"基金研究"，但未创建组合，可能需要产品引导和客服跟进。
  - 代表用户：钱七、孙八

  分群4：策略爱好者
  - 特征：频繁使用"因子管理"、"策略管理"，喜欢自定义因子和回测。
  - 代表用户：周九
  `;

  const handleSendChat = async () => {
    if (!chatInput.trim()) return;
    setChatLoading(true);
    setChatHistory(h => [...h, { role: 'user', content: chatInput }]);
    try {
      const res = await fetch('/api/analytics/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ question: chatInput })
      });
      const data = await res.json();
      setChatHistory(h => [...h, { role: 'ai', content: data.answer || 'AI暂无回复' }]);
    } catch (e) {
      setChatHistory(h => [...h, { role: 'ai', content: 'AI服务异常，请稍后再试。' }]);
    }
    setChatInput('');
    setChatLoading(false);
  };

  useEffect(() => {
    setSegLoading(true);
    fetch('/api/analytics/segmentation')
      .then(res => res.json())
      .then(data => {
        if (data && data.result && data.result.trim() !== '') {
          setSegmentation(data.result);
        } else {
          setSegmentation(mockSegmentation);
        }
        setSegLoading(false);
      })
      .catch(e => {
        setSegError(e.message);
        setSegmentation(mockSegmentation);
        setSegLoading(false);
      });
  }, []);

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '24px' }}>
        <h1>智能投资顾问系统</h1>
        <p>欢迎使用智能投资顾问系统，这里为您提供全方位的投资管理服务</p>
      </div>

      {/* 投资组合概览 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总资产"
              value={portfolioStats.totalValue}
              precision={0}
              valueStyle={{ color: '#3f8600' }}
              prefix="¥"
              suffix={
                <span style={{ fontSize: '14px', color: '#52c41a' }}>
                  <ArrowUpOutlined /> +{portfolioStats.totalReturn}%
                </span>
              }
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="日收益率"
              value={portfolioStats.dailyReturn}
              precision={2}
              valueStyle={{ color: portfolioStats.dailyReturn > 0 ? '#3f8600' : '#cf1322' }}
              prefix={portfolioStats.dailyReturn > 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
              suffix="%"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="月收益率"
              value={portfolioStats.monthlyReturn}
              precision={2}
              valueStyle={{ color: portfolioStats.monthlyReturn > 0 ? '#3f8600' : '#cf1322' }}
              prefix={portfolioStats.monthlyReturn > 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
              suffix="%"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="风险等级"
              value={portfolioStats.riskLevel === 'low' ? '低风险' : portfolioStats.riskLevel === 'medium' ? '中风险' : '高风险'}
              valueStyle={{ 
                color: portfolioStats.riskLevel === 'low' ? '#52c41a' : 
                       portfolioStats.riskLevel === 'medium' ? '#faad14' : '#f5222d' 
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* 快速操作 */}
      <Card title="快速操作" style={{ marginBottom: '24px' }}>
        <Row gutter={16}>
          {quickActions.map((action, index) => (
            <Col span={4} key={index}>
              <Card
                hoverable
                style={{ textAlign: 'center', cursor: 'pointer' }}
                onClick={() => handleQuickAction(action.path)}
              >
                <div style={{ fontSize: '24px', color: action.color, marginBottom: '8px' }}>
                  {action.icon}
                </div>
                <div>{action.title}</div>
              </Card>
            </Col>
          ))}
        </Row>
      </Card>

      {/* 功能演示 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={12}>
          <Card title="功能演示">
            <List
              size="small"
              dataSource={[
                '✅ 基金研究：新增基金、查看画像、编辑信息',
                '✅ 因子管理：新建因子、设置权重、查看详情',
                '✅ 策略管理：创建策略、启动/停止、风险控制',
                '✅ 投资组合：配置基金、权重分配、收益预测',
                '✅ 交易管理：订单审核、执行交易、状态跟踪'
              ]}
              renderItem={(item) => (
                <List.Item>
                  {item}
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card title="系统状态">
            <div style={{ marginBottom: '16px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                <span>数据库连接</span>
                <Tag color="green">正常</Tag>
              </div>
              <Progress percent={100} size="small" />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                <span>策略引擎</span>
                <Tag color="green">运行中</Tag>
              </div>
              <Progress percent={85} size="small" />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                <span>交易系统</span>
                <Tag color="green">正常</Tag>
              </div>
              <Progress percent={95} size="small" />
            </div>
            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                <span>风控系统</span>
                <Tag color="green">监控中</Tag>
              </div>
              <Progress percent={90} size="small" />
            </div>
          </Card>
        </Col>
      </Row>

      {/* 最近交易订单 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={12}>
          <Card 
            title="最近交易订单" 
            extra={
              <Button type="link" onClick={() => navigate('/trade')}>
                查看全部
              </Button>
            }
          >
            <Table
              dataSource={recentOrders}
              columns={orderColumns}
              pagination={false}
              size="small"
              rowKey="id"
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card 
            title="热门基金" 
            extra={
              <Button type="link" onClick={() => navigate('/fund-research')}>
                查看全部
              </Button>
            }
          >
            <Table
              dataSource={topFunds}
              columns={fundColumns}
              pagination={false}
              size="small"
              rowKey="code"
            />
          </Card>
        </Col>
      </Row>

      {/* 使用说明 */}
      <Card title="使用说明">
        <Row gutter={16}>
          <Col span={8}>
            <h4>🎯 开始使用</h4>
            <p>1. 点击上方"快速操作"中的任意功能</p>
            <p>2. 在对应页面点击"新增"按钮</p>
            <p>3. 填写表单信息并保存</p>
          </Col>
          <Col span={8}>
            <h4>📊 数据管理</h4>
            <p>• 所有数据实时保存</p>
            <p>• 支持编辑和删除操作</p>
            <p>• 提供搜索和筛选功能</p>
          </Col>
          <Col span={8}>
            <h4>⚡ 功能特色</h4>
            <p>• 完整的CRUD操作</p>
            <p>• 表单验证和错误提示</p>
            <p>• 响应式设计</p>
          </Col>
        </Row>
      </Card>

      <div style={{ marginBottom: '24px' }}>
        <Card title="AI智能问答" bordered={false}>
          <div style={{ background: '#f6f8fa', padding: 12, borderRadius: 4, minHeight: 200, marginBottom: 8, maxHeight: 300, overflowY: 'auto' }}>
            {chatHistory.length === 0 && <div style={{ color: '#888' }}>你可以向AI提问任何与本系统相关的问题</div>}
            {chatHistory.map((msg, idx) => (
              <div key={idx} style={{ margin: '8px 0', textAlign: msg.role === 'user' ? 'right' : 'left' }}>
                <span style={{ fontWeight: msg.role === 'user' ? 'bold' : 'normal', color: msg.role === 'user' ? '#1890ff' : '#222' }}>
                  {msg.role === 'user' ? '你：' : 'AI：'}
                </span>
                <span style={{ display: 'inline-block', maxWidth: '90%' }}>
                  {msg.role === 'ai'
                    ? <ReactMarkdown>{msg.content}</ReactMarkdown>
                    : msg.content}
                </span>
              </div>
            ))}
            {chatLoading && <div style={{ color: '#aaa' }}>AI正在思考...</div>}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <input
              style={{ flex: 1, padding: 6, borderRadius: 4, border: '1px solid #ccc' }}
              value={chatInput}
              onChange={e => setChatInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') handleSendChat(); }}
              placeholder="请输入你的问题"
              disabled={chatLoading}
            />
            <Button type="primary" onClick={handleSendChat} loading={chatLoading}>发送</Button>
          </div>
        </Card>
      </div>
    </div>
  );
};

export default Dashboard; 